<template>
  <XcDrawer ref="drawer" :title="$t('page.app.config')" :width="640" @onDrawerSave="onSave">
    <Tabs type="card" class="tab" v-model="current" :before-remove="deleteProfileConfirm" @on-tab-remove="deleteProfile">
      <TabPane v-for="(config, i) in configs" :key="i" :label="config.label" :closable="!!config.profile">
        <ConfigSet :ref="config.label" :profile="config.profile" :properties="config.properties" @onChanged="onProfileChanged" />
      </TabPane>
      <Dropdown v-if="!dependable" :transfer="true" trigger="click" @on-click="addProfile" slot="extra">
        <a href="javascript:void(0)">
          {{$t('page.app.profileadd')}}
          <Icon type="ios-arrow-down"></Icon>
        </a>
        <DropdownMenu slot="list">
          <DropdownItem name="dev">dev</DropdownItem>
          <DropdownItem name="test">test</DropdownItem>
          <DropdownItem name="prod">prod</DropdownItem>
          <DropdownItem name="custom" divided>自定义</DropdownItem>
        </DropdownMenu>
      </Dropdown>
    </Tabs>
  </XcDrawer>
</template>

<script>
  import XcDrawer from '@/components/xcdrawer'
  import ConfigSet from './configset'
  export default {
    name: "comp-configtab",
    components: { XcDrawer, ConfigSet },
    props: {
      dependable: Boolean,
    },
    data() {
      return {
        appname: String,
        configs: [],
        custom: '',
        current: '',
      }
    },
    watch: {
      appname(val) {
        this.loadConfig()
      }
    },
    methods: {
      show(name) {
        this.appname = name
        this.$refs.drawer.show()
      },
      loadConfig() {
        if (!this.appname) return
        // 获取配置
        this.configs = []
        this.$md.dispatch('app_config_list', {
          appname: this.appname
        }).then(data => {
          let configs = data.data || []
          for (let i in configs) {
            configs[i].label = this.appname + (configs[i].profile ? ('(' + configs[i].profile + ')') : '')
          }
          this.configs = configs
          if (configs.length === 0) this.addConfig('', '{}')
        })
      },
      addConfig(profile, properties) {
        let label = this.appname + (profile ? ('(' + profile + ')') : '')
        let app = this.$collect.findByProp(this.configs, 'label', label)
        if (app) {
          app.properties = properties
        } else {
          this.configs.push({ name: this.appname, profile: profile, label: label, properties: properties })
        }
      },
      addProfile(profile) {
        let that = this
        if ('custom' === profile) {
          that.$Modal.confirm({
            render: (h) => {
              return h('Input', {
                props: { placeholder: that.$t('page.app.profilecustom') },
                on: { input: (val) => { that.custom = val } }
              })
            },
            onOk() { that.doProfileAdd(that.custom) },
          })
        } else {
          that.doProfileAdd(profile)
        }
      },
      doProfileAdd(profile) {
        profile = profile.toLowerCase()
        if (!/^[a-z][a-z0-9]*/.test(profile)) {
          this.$Message.info(this.$t('page.app.profilecustomrule'))
          return
        }
        let label = this.appname + (profile ? ('(' + profile + ')') : '')
        let app = this.$collect.findByProp(this.configs, 'label', label)
        if (app) {
          this.$Message.info(this.$t('page.app.prifilealready'))
          return
        }
        // 增加Profile
        this.addConfig(profile, '{}')
      },
      deleteProfileConfirm(index) {
        let that = this
        that.$Modal.confirm({
          title: this.$t('delmodel.title'),
          content: this.$t('delmodel.content'),
          onOk() {
            that.deleteProfile(index)
          },
        })
        return new Promise(function (resolve, reject) { })
      },
      deleteProfile(index) {
        if (index === 0) return
        let d = this.configs.splice(index, 1)
        if (index === this.current) { this.current = 0 }
      },
      onProfileChanged(profile, proplist) {
        let prop
        let propmap = {}
        for (let i in proplist) {
          prop = proplist[i]
          if (prop.name && /^[a-z][a-zA-Z0-9_-]{1,55}/.test(prop.name)) propmap[prop.name] = prop.value
        }
        this.addConfig(profile, JSON.stringify(propmap))
      },
      onSave() {
        // 保存配置
        let configs = []
        let config
        for (let i in this.configs) {
          config = this.configs[i]
          configs.push({
            profile: config.profile,
            properties: config.properties,
          })
        }
        this.$md.dispatch('app_config_save', {
          appname: this.appname,
          dependable: this.dependable,
          configs: configs,
        }).then(data => {
          if (data.retCode === 1) {
            this.$Message.success(this.$t('submitok'))
            this.$refs.drawer.close(true)
          }
        })
      }
    }
  };
</script>
